<template>
  <pageHeader title="车间工序配置" :breadCrumb="['工厂建模', '车间工序配置']" />

  <a-spin :loading="workshopPage.pageLoading.value || loading" class="box">
    <div class="box-left">
      <a-input-search
        search-button
        v-model="searchForm.keyWord"
        style="width: 220px; margin-left: 20px; margin-top: 1px"
        placeholder="车间编码"
        @change="workshopPage.loadData"
        @search="workshopPage.loadData"
      />
      <div class="table">
        <a-row>
          <a-col
            v-for="header in workShowHeader"
            :span="header.span"
            :key="header.name"
          >
            <div class="lattice head">{{ header.name }}</div>
          </a-col>
        </a-row>
        <a-row
          v-for="(item, index) in workshopPage.pageList.value"
          :key="index"
          class="lattice content"
          :class="workshopChoiceId === item.id ? 'choice' : ''"
          @click="
            () => {
              workshopChoiceId = item.id;
              processGroupChoiceId = 0;
            }
          "
        >
          <a-col
            v-for="header in workShowHeader"
            :span="header.span"
            :key="header.name"
          >
            <div class="lattice">{{ item[header.code] }}</div>
          </a-col>
        </a-row>
        <a-empty v-show="!workshopPage.pageList.value.length" />
        <div class="pagination">
          <a-pagination
            simple
            :total="workshopPage.paginationTotal.value"
            :current="workshopPage.paginationCurrent.value"
            @change="workshopPage.pageChange($event, 'page')"
            @page-size-change="workshopPage.pageChange($event, 'size')"
          />
        </div>
      </div>
    </div>
    <div class="box-right">
      <a-empty v-show="!workshopChoiceId" />
      <div class="processGroupBox" v-show="!!workshopChoiceId">
        <div class="buts">
          <a-space>
            <WorkSerialChoice @choice="workSerialChoice">
              <a-button type="primary">添加工序</a-button>
            </WorkSerialChoice>

            <WorkSerialGroupChoice @choice="workSerialChoice">
              <a-button type="primary">添加工序组</a-button>
            </WorkSerialGroupChoice>
          </a-space>
          <a-button @click="processGroupPage.loadData">刷新</a-button>
        </div>
        <div class="table">
          <a-row class="content">
            <a-col
              v-for="header in processGroupHeaders"
              :span="header.span"
              :key="header.name"
            >
              <div class="lattice head">{{ header.name }}</div>
            </a-col>
          </a-row>
          <a-row
            v-for="(item, index) in processGroupPage.pageList.value"
            :key="index"
            class="content"
            :class="processGroupChoiceId === item.id ? 'choice' : ''"
            @click="processGroupChoiceId = item.id"
          >
            <a-col
              v-for="header in processGroupHeaders"
              :span="header.span"
              :key="header.name"
            >
              <div class="lattice">
                {{
                  item.processGroupData[0] && header.code
                    ? item.processGroupData[0][header.code]
                    : ''
                }}
                <a-popconfirm
                  content="是否删除该数据?"
                  v-if="header.name === '操作'"
                  type="error"
                  @ok="del([item.id])"
                >
                  <a-link status="danger"> 删除 </a-link>
                </a-popconfirm>
              </div>
            </a-col>
          </a-row>
          <a-empty v-if="!processGroupPage.pageList.value.length" />
          <div class="pagination">
            <a-pagination
              simple
              :total="processGroupPage.paginationTotal.value"
              :current="processGroupPage.paginationCurrent.value"
              @change="processGroupPage.pageChange($event, 'page')"
              @page-size-change="processGroupPage.pageChange($event, 'size')"
            />
          </div>
        </div>
      </div>

      <a-empty v-show="!!workshopChoiceId && !processGroupChoiceId" />
      <div
        class="resourcesBox"
        v-show="!!workshopChoiceId && !!processGroupChoiceId"
      >
        <a-tabs v-model:active-key="resourcesType">
          <template #extra>
            <div v-show="resourcesType === '2'">
              <ProductionLineChoice @choice="({id}:any) => addResources(id, 2)">
                <a-button>添加产线</a-button>
              </ProductionLineChoice>
            </div>
            <div v-show="resourcesType === '1'">
              <StationChoice
                @choice="(data:any[]) => addResources(data[0].id, 1)"
              >
                <a-button>添加工位</a-button>
              </StationChoice>
            </div>
            <div v-show="resourcesType === '3'">
              <EquipmentChoice
                v-show="resourcesType === '3'"
                :workshopld="workshopChoiceId"
                @choice="({ id }) => addResources(id, 3)"
              >
                <a-button>添加设备</a-button>
              </EquipmentChoice>
            </div>
          </template>
          <a-tab-pane key="2" title="产线" />
          <a-tab-pane key="1" title="工位" />
          <a-tab-pane key="3" title="设备" />
        </a-tabs>

        <tableTurn :tableData="getResourcesPage" ref="tableRef">
          <a-table-column
            v-for="header in resourcesType === '2'
              ? productionLineHerders
              : resourcesType === '1'
              ? stationHerders
              : equipmentHeaders"
            :key="header.name"
            :width="200"
            :title="header.name"
            :data-index="header.code"
            align="center"
          >
            <template #cell="{ record }">
              <template v-if="header.name === '状态'">
                <a-typography-text type="success" v-if="record.state === 1">
                  启用
                </a-typography-text>
                <a-typography-text type="danger" v-if="record.state === 2">
                  停用
                </a-typography-text>
              </template>
              <template v-else>
                {{ getResourcesValue(record, resourcesType, header.code) }}
              </template>
            </template>
          </a-table-column>
          <a-table-column :width="80" fixed="right" title="操作" align="center">
            <template #cell="{ record }">
              <a-space>
                <a-popconfirm
                  content="是否删除该数据?"
                  type="error"
                  @ok="delResources([record.id])"
                >
                  <a-link status="danger"> 删除 </a-link>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </tableTurn>
      </div>
    </div>
  </a-spin>
</template>

<script setup lang="ts">
  import { reactive, onMounted, ref, watch } from 'vue';
  import {
    GetWorkshopPage,
    GetdFactorySet,
    AddFactorySet,
    DelFactorySet,
    AddResources,
    DelResources,
    GetResourcesPage,
  } from '@/api/FactoryModeling';
  import WorkSerialChoice from '@/views/client-side/FactoryModeling/components/WorkSerialChoice.vue';
  import WorkSerialGroupChoice from '@/views/client-side/FactoryModeling/components/WorkSerialGroupChoice.vue';
  import ProductionLineChoice from '@/views/client-side/FactoryModeling/components/ProductionLineChoice.vue';
  import StationChoice from '@/views/client-side/FactoryModeling/components/StationChoice.vue';

  import EquipmentChoice from '@/views/client-side/FactoryModeling/components/EquipmentChoice.vue';
  import useTurn from '@/hooks/useTurn';
  import { Message } from '@arco-design/web-vue';

  let getResourcesValue = (record: any, type: string, code?: string) => {
    let data =
      record[
        type === '1'
          ? 'stationProcessGroupData'
          : type === '2'
          ? 'lineProcessGroupData'
          : 'deviceProcessGroupData'
      ];
    if (type === '3') return record[code + ''];
    data = Array.isArray(data) ? data[0] : false;
    if (data) {
      return data[code + ''];
    }
  };

  let workshopChoiceId = ref(0);
  let processGroupChoiceId = ref(0);
  let resourcesType = ref<any>('2');
  let searchForm = reactive<any>({});
  let loading = ref(false);
  let rightList = ref<any[]>([]);
  let tableRef = ref();
  let addResources = async (id: number, type: number) => {
    await AddResources({
      type,
      processSetId: processGroupChoiceId.value,
      deviceId: type === 3 ? id : undefined,
      stationId: type === 1 ? id : undefined,
      lineId: type === 2 ? id : undefined,
    });
    tableRef.value.loadData();
  };
  let processGroupPage = useTurn<any>(async (page: any) => {
    try {
      let res = await GetdFactorySet({
        workshopId: workshopChoiceId.value,
        ...page,
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      return Promise.reject();
    }
  });
  watch(workshopChoiceId, () => processGroupPage.loadData());

  let del = async (ids: any[]) => {
    await DelFactorySet(ids);
    processGroupPage.loadData();
  };

  let delResources = async (ids: any[]) => {
    await DelResources(ids);
    tableRef.value.loadData();
  };
  let workSerialChoice = async ([{ id }]: any[]) => {
    if (!rightList.value.some(({ processGroupId }) => processGroupId === id)) {
      await AddFactorySet({
        workshopId: workshopChoiceId.value,
        processGroupId: id,
      });
      processGroupPage.loadData();
    } else {
      Message.error('不可重复添加');
    }
  };

  let workShowHeader = [
    { name: '车间编码', code: 'code', span: 13 },
    { name: '车间名称', code: 'name', span: 11 },
  ];
  let workshopPage = useTurn<any>(async (page: any) => {
    try {
      let res = await GetWorkshopPage({
        ...page,
        ...searchForm,
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      return Promise.reject();
    }
  }, 5);
  watch(resourcesType, () => tableRef.value.loadData());
  watch(processGroupChoiceId, () => tableRef.value.loadData());
  let getResourcesPage = async (page: any) => {
    try {
      let res = await GetResourcesPage({
        ...page,
        processSetId: processGroupChoiceId.value,
        type: resourcesType.value,
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  let processGroupHeaders = [
    { name: '工序编码', code: 'processCode', span: 5 },
    { name: '工序名称', code: 'processName', span: 5 },
    { name: '工序说明', code: 'remark', span: 5 },
    { name: '工序类别', code: 'processType', span: 5 },
    { name: '操作', span: 4 },
  ];

  const stationHerders = [
    { code: 'stationCode', name: '工位编码' },
    { code: 'stationName', name: '工位名称' },
    { code: 'remark', name: '备注' },
  ];

  const productionLineHerders = [
    { code: 'lineCode', name: '产线编码' },
    { code: 'lineName', name: '产线名称' },
    { code: 'remark', name: '备注' },
  ];

  let equipmentHeaders = [
    { code: 'deviceCoding', name: '设备编码' },
    { code: 'deviceName', name: '设备名称' },
    { code: 'specification', name: '规格', width: 100 },
    { code: 'modelNumber', name: '型号', width: 100 },
  ];
</script>

<style lang="less" scoped>
  .box {
    display: flex;
    width: 100%;
    height: 700px;
    &-right {
      width: 100%;
      height: 100%;
      .buts {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        margin-left: 20px;
      }
    }
    &-left {
      height: 100%;
      width: 400px;
      border-right: 1px solid var(--color-neutral-3);
    }
  }

  .table {
    margin-top: 10px;
    margin-bottom: 20px;
    .lattice {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 40px;
      text-align: center;
      border-bottom: 1px solid var(--color-neutral-3);
      padding: 0 10px;
    }
    .content:hover {
      background-color: rgb(var(--arcoblue-1));
      cursor: pointer;
    }
    .head {
      background-color: var(--color-neutral-2);
    }
    .choice {
      background-color: rgb(var(--arcoblue-1));
    }
    .pagination {
      margin-top: 10px;
    }
  }
</style>
